import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { ConfigProvider, App as AntApp } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { AppProvider, useAppContext } from './contexts/AppContext';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import ToolManagement from './pages/ToolManagement';
import ConfigManagement from './pages/ConfigManagement';
import UserManagement from './pages/UserManagement';
import Layout from './components/Layout';
import PrivateRoute from './components/PrivateRoute';
import Loading from './components/Loading';
import './App.css';

// 设置dayjs本地化
dayjs.locale('zh-cn');

// 主应用组件
const AppContent: React.FC = () => {
  const { state } = useAppContext();

  if (state.loading) {
    return <Loading />;
  }

  return (
    <Router>
      <Routes>
        {/* 公开路由 */}
        <Route 
          path="/login" 
          element={
            state.isAuthenticated ? <Navigate to="/dashboard" replace /> : <Login />
          } 
        />

        {/* 私有路由 */}
        <Route path="/" element={<PrivateRoute />}>
          <Route path="/" element={<Layout />}>
            <Route index element={<Navigate to="/dashboard" replace />} />
            <Route path="dashboard" element={<Dashboard />} />
            <Route path="tools/*" element={<ToolManagement />} />
            <Route path="configs/*" element={<ConfigManagement />} />
            <Route path="users/*" element={<UserManagement />} />
          </Route>
        </Route>

        {/* 404路由 */}
        <Route 
          path="*" 
          element={
            <div style={{ 
              display: 'flex', 
              justifyContent: 'center', 
              alignItems: 'center', 
              height: '100vh',
              flexDirection: 'column',
              gap: '16px'
            }}>
              <h1>404</h1>
              <p>页面不存在</p>
              <a href="/dashboard">返回首页</a>
            </div>
          } 
        />
      </Routes>
    </Router>
  );
};

// 主App组件
const App: React.FC = () => {
  return (
    <ConfigProvider 
      locale={zhCN}
      theme={{
        token: {
          colorPrimary: '#1890ff',
          borderRadius: 6,
        },
      }}
    >
      <AntApp>
        <AppProvider>
          <AppContent />
        </AppProvider>
      </AntApp>
    </ConfigProvider>
  );
};

export default App;
